import 'package:flutter/material.dart';
import 'package:shenling/utils/http.dart';
import 'package:shenling/utils/toast.dart';
import 'package:shenling/utils/token.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 账号密码输入框控制器
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  // 密码可见性控制变量
  bool _isPasswordVisible = true;
  @override
  void initState() {
    super.initState();
    _accountController.text = 'Bryant132430';
    _passwordController.text = '123456';
  }

  // 提交
  void _submit() async {
    // 获取账号和密码
    String account = _accountController.text;
    String password = _passwordController.text;

    // 验证账号和密码
    if (account.isEmpty || password.isEmpty) {
      return ToastUtil.showError('请输入账号和密码');
    }

    // 调接口登录
    try {
      var res = await dioHttp.post('/driver/login/account',
          data: {"account": account, "password": password});
      if (res['code'] == 200) {
        // 登录成功
        print(res);
        // 存储token
        await TokenManager().saveToken(res['data']);
        ToastUtil.showSuccess('登录成功');

        // 跳转到首页 - 替换登录页
        // ignore: use_build_context_synchronously
        Navigator.pushReplacementNamed(context, '/'); // 假设首页路由为 '/home'
      } else {
        // 登录失败
        ToastUtil.showError(res['msg']);
      }
    } catch (e) {
      // print(e);
      ToastUtil.showError('登录失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            '神领快递',
            style: TextStyle(fontSize: 18),
          ),
          centerTitle: true,
          automaticallyImplyLeading: false,
        ),
        body: Padding(
          padding: const EdgeInsets.only(left: 20, right: 20, top: 50),
          child: Column(children: [
            const Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '账号登录',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                Text(
                  '手机号登录',
                  style:
                      TextStyle(color: Colors.red, fontWeight: FontWeight.w800),
                ),
              ],
            ),
            const SizedBox(height: 20),
            TextField(
              controller: _accountController,
              decoration: const InputDecoration(
                hintText: '请输入用户名',
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                      color: Color.fromARGB(255, 214, 213, 213)), // 正常状态下的下划线颜色
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.black, width: 2.0), // 获得焦点时的下划线颜色和宽度
                ),
              ),
            ),

            const SizedBox(height: 20),
            // 密码输入不可见，带眼睛图标控制密码显隐
            TextField(
              controller: _passwordController,
              obscureText: !_isPasswordVisible,
              onChanged: (value) {
                setState(() {
                  // 触发重新构建以更新清除图标状态
                });
              },
              decoration: InputDecoration(
                hintText: '请输入密码',
                enabledBorder: const UnderlineInputBorder(
                  borderSide:
                      BorderSide(color: Color.fromARGB(255, 214, 213, 213)),
                ),
                focusedBorder: const UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black, width: 2.0),
                ),
                suffixIcon: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 清除图标 - 仅在有内容时显示
                    if (_passwordController.text.isNotEmpty)
                      IconButton(
                        icon: const Icon(Icons.clear),
                        onPressed: () {
                          setState(() {
                            _passwordController.clear();
                          });
                        },
                      ),
                    // 眼睛图标 - 控制密码可见性
                    IconButton(
                      icon: Icon(
                        _isPasswordVisible
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _isPasswordVisible = !_isPasswordVisible;
                        });
                      },
                    ),
                  ],
                ),
              ),
            ),

            // 登录按钮， 背景色为红色，文字白色，距离左右都为30，距离上方50
            // 登录按钮， 背景色为红色，文字白色，距离左右都为30，距离上方50
            // 登录按钮， 背景色为红色，文字白色，距离左右都为30，距离上方50
            Padding(
              padding: const EdgeInsets.only(left: 15, right: 15, top: 30),
              child: SizedBox(
                height: 50,
                width: double.infinity, // 水平方向撑满
                child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor: WidgetStateProperty.all(Colors.red),
                    foregroundColor: WidgetStateProperty.all(Colors.white),
                  ),
                  onPressed: () {
                    // 登录按钮点击事件
                    _submit();
                  },
                  child: const Text('登录'),
                ),
              ),
            )
          ]),
        ));
  }
}
